package ljl.alg.jianzhioffer.round2;

/**
 * 啪一下，很快啊，直接复制粘贴
 * */
public class _43_count1 {
    
    /**
     * 这个题，统计从 1 到 n 所有数里 1 出现的次数
     * 不得不说这是一个智力题，很难！
     * */
    /*
    * */
    public int countDigitOne_official(int n) {
        int digit = 1, res = 0;
        int high = n / 10, cur = n % 10, low = 0;
        while(high != 0 || cur != 0) {
            // [0, high - 1] 这么多个 digit
            if(cur == 0) res += high * digit;
            // [0, high - 1] * digit + [0, low]
            else if(cur == 1) res += high * digit + low + 1;
            // [0, high]
            else res += (high + 1) * digit;
            low += cur * digit;
            cur = high % 10;
            high /= 10;
            digit *= 10;
        }
        return res;
    }
    
    public int countDigitOne(int n) {
        int digit = 1, high = n / 10, low = 0, cur = n % 10;
        int res = 0;
        while (high >= 0 || cur >= 0) {
         
            if (cur == 0) {
                res += high * digit;
            } else if (cur == 1) {
                res += high * digit + low + 1;
            } else {
                res += (high + 1) * digit;
            }
            
            low += cur * digit;
            digit *= 10;
            cur = high % 10;
            high = high / 10;
        }
        return res;
    }
}
